<?php

/**
 * @name UserController
 * @desc 控制器
 */
class UserController extends UserCommonController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
//        print_r($this->user_info);exit;
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $this->user_info['user_id']]);

        //直接上级
        $referUser = $userModel->find(['user_id'=> $userInfo['refer_user_id']], 'moble');

        if(!$referUser){
            $userInfo['refer_user_moble'] = '无';
        }else {
            $userInfo['refer_user_moble'] = \Vendor\Kstring::hideMobile($referUser['moble']);
        }

        unset($userInfo['user_id']);
        unset($userInfo['login_pwd']);
        unset($userInfo['pay_pwd']);
        unset($userInfo['status']);
        unset($userInfo['create_time']);
        unset($userInfo['update_time']);

//        $userInfo['moble'] = \Vendor\Kstring::hideMobile($userInfo['moble']);
        $userInfo['wechat'] = isset($userInfo['wechat'])? $userInfo['wechat']: '';
        $userInfo['alipay'] = isset($userInfo['alipay'])? $userInfo['alipay']: '';

        $this->ajaxReturn(0, 'success', $userInfo);
    }

    public function userfullAction(){
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $this->user_info['user_id']]);
        unset($userInfo['user_id']);
        unset($userInfo['login_pwd']);
        unset($userInfo['pay_pwd']);
        unset($userInfo['status']);
        unset($userInfo['create_time']);
        unset($userInfo['update_time']);

//        $userInfo['moble'] = \Vendor\Kstring::hideMobile($userInfo['moble']);
        $userInfo['wechat'] = $userInfo['wechat']? $userInfo['wechat']: '';
        $userInfo['alipay'] = $userInfo['alipay']? $userInfo['alipay']: '';

        $shopInfo = [];
        if($userInfo['user_type'] != 0){
            $shopInfo = ShopModel::getSingleton()->find(['shop_id'=> $userInfo['shop_id']]);
            if($shopInfo['tags']){
                $temp = explode(',', $shopInfo['tags']);
                $arr = [];
                foreach ($temp as $val){
                    $arr[] = ShopModel::$shopTagsArr[$val]['text'];
                }
                $shopInfo['tags_text'] = implode(',', $arr);
            }
            $shopInfo['gallery_img'] = $shopInfo['gallery_img'] && $shopInfo['gallery_img']!='null'?json_decode($shopInfo['gallery_img'], true):[];
        }

        $this->ajaxReturn(0, 'success', ['userInfo'=> $userInfo, 'shopInfo'=> $shopInfo]);
    }

    //店铺绑定
    public function shopbindAction(){
        $params = $this->post();

        $userModel = UserModel::getSingleton();
        $userDetail = $userModel->find(['user_id'=> $this->user_info['user_id']]);

        if(!$userDetail['shop_id']){
            $userModel->update(['user_id'=> $this->user_info['user_id']], ['shop_id'=> $params['shop_id']]);
        }
    }

    //店铺信息
    public function shopinfoAction(){
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $this->user_info['user_id']]);


        $shopModel = ShopModel::getSingleton();
//        $shopInfo = $shopModel->find(['shop_id'=> $this->user_info['offline_shop_id']]);

        //直属店铺信息（非顶层实体店）
        $shopInfo = $userModel->db
            ->field('u.user_id,s.*')
            ->alias('u')
            ->join(['shop', 's'], ['u.user_id'=> 's.user_id'], 'inner join')
            ->where_c(['u.user_id'=> $userInfo['refer_user_id']])
            ->find();

        $shopInfo['gallery_img'] = json_decode($shopInfo['gallery_img'], true);
        $tagsArr = [];
        $shopInfo['tags'] = [];
        if($shopInfo['tags']){
            $temp = explode(',', $shopInfo['tags']);
            foreach ($temp as $val){
                $tagsArr[] = ShopModel::$shopTagsArr[$val];
            }
            $shopInfo['tags'] = $tagsArr;
        }

        $this->ajaxReturn(0, 'success', $shopInfo);
    }

    //分享二维码
    public function qrcodeAction()
    {

        //直推用户
        $userModel = UserModel::getSingleton();
        //1级子节点
        $topChild = $userModel->findAll(['refer_user_id'=> $this->user_info['user_id']],'*','user_id asc');
        //当前登录用户
        $thisUser = $userModel->find(['user_id'=> $this->user_info['user_id']]);

        $ruserData = [
            'rid1'  => '',
            'rid1_total'  => '',
            'rid2'  => '',
            'rid2_total'  => '',
        ];
        $count = count($topChild);

        $config = \Yaf\Application::app()->getConfig()->app;
        if( $count==0 ){

            $ruserData['rid1'] = $this->user_info['user_id'] + 1000;
            $ruserData['rid1_total'] = 0;
            $ruserData['rid2'] = $this->user_info['user_id'] + 1000;
            $ruserData['rid2_total'] = 0;
            $returnData = [
                'host'  => $config['h5_url'],
                'rids'   => $ruserData
            ];
            $this->ajaxReturn(0, 'success', $returnData);
        }

        $rid1 = $userModel->getReferTeamUser($topChild[0]);
        $rid1_total = $userModel->getGroupTotalCharge($topChild[0]['user_id']);


//        第一个团队
//        $sql = 'SELECT user_id,refer_num from h_user where FIND_IN_SET(user_id,fcGetTreeList('.$topChild[0]['user_id'].'))  and refer_num<2 and status=1';
//        $group1 = $userModel->db->query($sql);
//        $group1ReferID = $this->getReferByGroup($group1);

        if( $count == 1 ){
            $ruserData['rid1'] = $this->user_info['user_id'];
            $ruserData['rid1_total'] = $rid1_total[0]['total'];
            $ruserData['rid2'] = $rid1;
            $ruserData['rid2_total'] = 0;
            $returnData = [
                'host'  => $config['h5_url'],
                'rids'   => $ruserData
            ];
            $this->ajaxReturn(0, 'success', $returnData);
        }

        $rid2 = $userModel->getReferTeamUser($topChild[1]);
        $rid2_total = $userModel->getGroupTotalCharge($topChild[1]['user_id']);

//        第二个团队
//        $sql = 'SELECT user_id,refer_num from h_user where FIND_IN_SET(user_id,fcGetTreeList('.$topChild[1]['user_id'].'))  and refer_num<2 and status=1';
//        $group2 = $userModel->db->query($sql);
//        $group2ReferID = $this->getReferByGroup($group2);

        if( $count == 2 ){
            $ruserData['rid1'] = $rid1;
            $ruserData['rid1_total'] = $rid1_total[0]['total'];
            $ruserData['rid2'] = $rid2;
            $ruserData['rid2_total'] = $rid2_total[0]['total'];
        }

        $ruserData['rid1'] = $ruserData['rid1'] + 1000;
        $ruserData['rid2'] = $ruserData['rid2'] + 1000;

        $returnData = [
            'host'  => $config['h5_url'],
            'rids'   => $ruserData
        ];

        $this->ajaxReturn(0, 'success', $returnData);
    }

    //转入
    public function putAction(){
        $config = \Yaf\Application::app()->getConfig()->app;
        $returnData = [
            'host'  => $config['h5_url'],
            'rid'   => $this->user_info['user_id'] + 1000
        ];
        $this->ajaxReturn(0, 'success', $returnData);
    }

    /*
     * $top_user_id
     */
/*    private function getReferTeamUser($top_user_id){
        $userModel = UserModel::getSingleton();
        $res = $userModel->getReferTeamUser($top_user_id);
        return $res;
    }*/

    //获取团队推荐人（同样资金优先推荐先注册成员）
/*    private function getReferByGroup( $group ){
        if(!$group || empty($group)){
            return 0;
        }
        $newGroup1 = [];
        $newGroup0 = [];
        foreach($group as $val){
            if($val['refer_num'] == 1){
                $newGroup1[$val['user_id']] = $val;
            }else if($val['refer_num'] == 0){
                $newGroup0[$val['user_id']] = $val;
            }
        }
        ksort($newGroup1);
        ksort($newGroup0);
        return $newGroup1? reset($newGroup1)['user_id']: reset($newGroup0)['user_id'];
    }*/

    //验证账户
    public function getuserAction(){
        $id = $this->post('id');
        if(!$id || $id<1000){
            $this->ajaxReturn(400, 'ID错误');
        }

        $id = $id - 1000;

        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $id]);
        if(!$userInfo){
            $this->ajaxReturn(400, '账户不存在');
        }

        $this->ajaxReturn(0, 'success', [
            'nick_name' => $userInfo['nick_name'],
            'id'        => $userInfo['user_id'] + 1000
        ]);
    }

    //转出
    public function outAction(){
        $params = $this->post();
        $rule = [
            'id'        => 'require|egt:1000',
            'amount'    => 'require|number',
            'm_code'    => 'require|length:4'
        ];
        $msg = [
            'id.require' => '未获取到转入ID',
            'id.egt'   => '转入ID错误',
            'amount.require'  => '必须输入转入数量',
            'amount.number'  => '转入数量不合法',
            'm_code.require'    => '必须输入手机号后4位',
            'm_code.length'    => '需要输入手机号后4位'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //不能自己转自己
        if($params['id'] == $this->user_info['user_id']){
            $this->ajaxReturn(400, '不能转入自己账户');
        }

        $id = intval($params['id']) - 1000;
        $amount = $params['amount'];

        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $id]);
        if(!$userInfo){
            $this->ajaxReturn(400, '账户不存在');
        }
        //验证手机号后4位
        $lastCode = substr($userInfo['moble'], -4);
        if($lastCode != $params['m_code']){
            $this->ajaxReturn(400, '手机号后4位错误');
        }
        $thisUserInfo = $userModel->find(['user_id'=> $this->user_info['user_id']]);
        if($thisUserInfo['coin'] == 0 || $thisUserInfo['coin']<$amount){
            $this->ajaxReturn(400, '货币数量不足');
        }
        $userModel = UserModel::getSingleton();
        try{
            \Vendor\DB::startTrans();
            //主账户减扣
            $res = $userModel->setDec(['user_id'=> $this->user_info['user_id']], 'coin', $amount);
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '转账失败');
            }
            //充值账户增加
            $res = $userModel->setInc(['user_id'=> $id], 'coin', $amount);
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '转账失败');
            }

            $coinLogModel = CoinLogModel::getSingleton();

            //减扣记录
            $res = $coinLogModel->add([
                'charge_id' => 0,
                'type'  => 2,
                'cate'  => 2,   //2转出
                'user_id'=> $this->user_info['user_id'],
                'from_user_id'  => $id,
                'amount_before' => $thisUserInfo['coin'],
                'amount'    => $amount,
                'amount_after'  => $thisUserInfo['coin'] - $amount,
                'f_amount_before' => $thisUserInfo['f_coin'],
                'f_amount'    => 0,
                'f_amount_after'  => $thisUserInfo['f_coin'],
                'description'   => '['.CoinLogModel::$cateArr[3].']' . '转给' . $userInfo['moble'] . $amount
            ]);
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '充值失败');
            }
            //入账记录
            $res = $coinLogModel->add([
                'charge_id' => 0,
                'type'  => 1,
                'cate'  => 3,   //3转入
                'user_id'=> $id,
                'from_user_id'  => $this->user_info['user_id'],
                'amount_before' => $userInfo['coin'],
                'amount'    => $amount,
                'amount_after'  => $userInfo['coin'] + $amount,
                'f_amount_before' => $userInfo['f_coin'],
                'f_amount'    => 0,
                'f_amount_after'  => $userInfo['f_coin'],
                'description'   => '['.CoinLogModel::$cateArr[3].']' . '收到' . $userInfo['moble'] . $amount
            ]);

            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '转账失败');
            }

            \Vendor\DB::commit();
        }catch(\Yaf\Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '转账失败');
        }

        $this->ajaxReturn(0, 'success');
    }

    //修改个人资料
    public function editAction(){
        $params = $this->post();

        $exist = false;
        if(isset($params['nick_name']) && trim($params['nick_name'])){
            $exist = true;
            $length = mb_strlen((string) $params['nick_name']);
            if($length<1 || $length>8){
                $this->ajaxReturn(400, '昵称必须在1~8个字符之间');
            }
        }
        if(isset($params['wechat']) && trim($params['wechat'])){
            $exist = true;
            $length = mb_strlen((string) $params['wechat']);
            if($length<1 || $length>20){
                $this->ajaxReturn(400, '必须输入正确的微信号');
            }
        }
        if(isset($params['alipay']) && trim($params['alipay'])){
            $exist = true;
            $length = mb_strlen((string) $params['alipay']);
            if($length<1 || $length>20){
                $this->ajaxReturn(400, '必须输入正确的支付宝账号');
            }
        }
        if(!$exist){
            $this->ajaxReturn(400, '必须提交修改数据');
        }

        $editData = ['update_time'=> time()];
        if(isset($params['nick_name'])){
            $editData['nick_name'] = $params['nick_name'];
        }
        if(isset($params['wechat'])){
            $editData['wechat'] = $params['wechat'];
        }
        if(isset($params['alipay'])){
            $editData['alipay'] = $params['alipay'];
        }

        $userModel = UserModel::getSingleton();
        if(!$userModel->update(['user_id'=> $this->user_info['user_id']], $editData)){
            $this->ajaxReturn(400, '修改失败');
        }

        $this->ajaxReturn(0, 'success');
    }

    public function editprofileAction(){
        $params = $this->post();
        $rule = [
            'type'      => 'require',
            'index'     => 'require',
            'value'     => 'require'
        ];
        $msg = [
            'type.require' => '参数不正确',
            'index.require'   => '参数不正确',
            'value.require'  => '参数不正确',
            'value.length'  => '长度超出限制',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        if($params['index'] == 'moble'){
            if(!preg_match('/^1[345678]{1}\d{9}$/', $params['value'], $matches)){
                $this->ajaxReturn(400, '必须输入正确的手机号');
            }
            //验证手机号是否被注册
            if(UserModel::getSingleton()->find(['moble'=> $params['value']])){
                $this->ajaxReturn(400, '手机号已经被绑定');
            }
        }
        if($params['index'] == 'wechat'){
            if(!preg_match('/^.{5,20}$/', $params['value'], $matches)){
                $this->ajaxReturn(400, '必须输入正确的微信号');
            }
        }
        if($params['index'] == 'shop_name'){
            if(!preg_match('/^.{1,60}$/', $params['value'], $matches)){
                $this->ajaxReturn(400, '店铺名称不能太长');
            }
        }
        if($params['index'] == 'shop_description'){
            if(!preg_match('/^.{1,60}$/', $params['value'], $matches)){
                $this->ajaxReturn(400, '店铺名简称应在20个字符以内');
            }
        }
        if($params['index'] == 'address'){
            if(!preg_match('/^.{1,150}$/', $params['value'], $matches)){
                $this->ajaxReturn(400, '店铺地址应在50个字符以内');
            }
        }
        if($params['index'] == 'mobile'){
            if(!preg_match('/^.{1,40}$/', $params['value'], $matches)){
                $this->ajaxReturn(400, '店铺联系方式在35个字符以内');
            }
        }

        if($params['type'] == 1){
            $model = UserModel::getSingleton();
            if(!$model->update(['user_id'=> $this->user_info['user_id']], [$params['index']=> $params['value'], 'update_time'=> time()])){
                $this->ajaxReturn(400, '修改失败');
            }
        }else {
            $userInfo = UserModel::getSingleton()->find(['user_id'=> $this->user_info['user_id']]);
            $model = ShopModel::getSingleton();
            if($params['index'] == 'tags'){
                foreach ($params['value'] as $key=> &$val){
                    if($val == ',' || $val== ''){
                        unset($params['value'][$key]);
                    }
                }
                sort($params['value']);
                $params['value'] = implode(',', $params['value']);
            }

            if(!$model->update(['shop_id'=> $userInfo['shop_id']], [$params['index']=> $params['value'], 'update_time'=> time()])){
                $this->ajaxReturn(400, '修改失败');
            }
        }

        $this->ajaxReturn(0, 'success');
    }

    //修改手机号
    public function editmobleAction(){
        $params = $this->post();
        $rule = [
            'moble'     => 'require|regex:moble',
            'sms_code'  => 'require',
        ];
        $msg = [
            'moble.require' => '必须输入手机号',
            'moble.regex'   => '手机号格式错误',
            'sms_code.require'  => '必须输入短信验证码',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $sms = new \Vendor\ext\Sms();
        if($sms->checkSms($params['moble'], $params['sms_code'], 'edit_moble')){
            $this->ajaxReturn(400, $sms->errMsg);
        }

        $userModel = UserModel::getSingleton();
        $exist = $userModel->find(['moble'=> $params['moble']], 'user_id');
        if($exist){
            $this->ajaxReturn(400, '手机号已注册');
        }

        $userInfo = $userModel->find(['user_id'=> $this->user_info['user_id']]);
        $temp = explode(',', $userInfo['history_moble']);
        array_push($temp, $userInfo['moble']);
        $upData = [
            'moble' => $params['moble'],
            'history_moble' => implode(',', $temp),
            'update_time'   => time()
        ];

        if(!$userModel->update(['user_id'=> $this->user_info['user_id']], $upData)){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, '修改成功');
    }

    //上传头像
    public function uploadimgAction(){
        $params = $this->post();
//        if(isset($params['type'])){
//
//            if (!isset($_FILES['filedata'])) {
//                $this->ajaxReturn(400, '文件数据字段名为“filedata”');
//            }
//            $tmpName = $_FILES['filedata']['tmp_name'];
//
//            $file = '';
//            try {
//                $file = (new \Vendor\FileModel($tmpName))->setUploadInfo($_FILES['filedata']);
//            } catch (Exception $e) {
//                $this->ajaxReturn(1,'请选择上传文件');
//            }
//
//            $file->validate(['size' => 1024 * 1024 * 10, 'ext' => 'jpg,png,jpeg']);
//            $info = $file->move(APP_PATH . '/public/upload/' . $params['type']);
//            if (!$info) {
//                $this->ajaxReturn(1,$file->getError());
//            }
//
//            $img_url = \Vendor\Kstring::image_domain_url('/upload/'.$info->getSaveName());
//
//            //头像上传
//            if($params['type'] == 'head_img'){
//                $userModel = UserModel::getSingleton();
//                $userModel->update(['user_id'=> $this->user_info['user_id']], ['head_img'=> $img_url]);
//            }
//
//            $this->ajaxReturn(0,'上传成功', $img_url);
//
//        }else {


//            $data = file_get_contents("php://input");

            if(!isset($params['type'])){
                $this->ajaxReturn(400, '必须指定上传类型');
            }
            if(!isset($params['filedata'])){
                $this->ajaxReturn(400, '未获取到图片数据');
            }

            $data = $params['filedata'];
            $img_base64 = explode('base64,', $data);
            if (!$img_base64) {
                $this->ajaxReturn(400, '未获取到图片数据');
            }
            $img = base64_decode(trim($img_base64[1]));
            $img_type = explode('/', trim($img_base64[0], ';'));
            switch (strtolower($img_type[1])) {
                case 'jpeg':
                case 'jpg':
                    $img_suffix = "jpg";
                    break;
                case 'png':
                    $img_suffix = "png";
                    break;
                case 'gif':
                    $img_suffix = "gif";
                    break;
                default:
                    $img_suffix = "jpg";
            }
            $path_config = \Yaf\Application::app()->getConfig()->upload;
            $curDate = date('Ymd');
            $save_path = $path_config['path']. '/' . $params['type'] . '/' . $curDate;
            if (!is_dir($save_path)) {
                if (!mkdir($save_path, 0755, true)) {
                    $this->ajaxReturn(400, '上传失败，文件目录不存在');
                }
            }
            $img_name =   '/' . md5(rand(1, 60000)) . "." . $img_suffix;
            file_put_contents($save_path . $img_name, $img);

            $img_url = \Vendor\Kstring::image_domain_url('/upload/'.$params['type'].'/' . $curDate .'/'. $img_name);
//            $img_url = \Vendor\Kstring::image_domain_url('/upload/'. $curDate . $img_name);

            //头像上传
            if($params['type'] == 'head_img'){
                $userModel = UserModel::getSingleton();
                $userModel->update(['user_id'=> $this->user_info['user_id']], ['head_img'=> $img_url]);
            }
            //店铺头像
            if($params['type'] == 'shop_logo'){
                $userInfo = UserModel::getSingleton()->find(['user_id'=> $this->user_info['user_id']]);
                ShopModel::getSingleton()->update(['shop_id'=> $userInfo['shop_id']], ['logo'=> $img_url]);
            }
            //店铺轮播图
            if($params['type'] == 'shop_gallery_img'){
                $shopModel = ShopModel::getSingleton();
                $userInfo = UserModel::getSingleton()->find(['user_id'=> $this->user_info['user_id']]);
                $shopInfo = $shopModel->find(['shop_id'=> $userInfo['shop_id']]);
                $gallery_img = json_decode($shopInfo['gallery_img'], true);
                $gallery_img = is_array($gallery_img)? $gallery_img: [];
                array_push($gallery_img, ['url'=> $img_url]);
                ShopModel::getSingleton()->update(['shop_id'=> $userInfo['shop_id']], ['gallery_img'=> json_encode($gallery_img)]);
            }

            $this->ajaxReturn(0, 'success', $img_url);
//        }
    }

    //分享链接
    public function share1Action(){

        $userInfo = UserModel::getSingleton()->find(['user_id'=> $this->user_info['user_id']], 'user_id,user_type');
        if($userInfo['user_type'] == 0){
            $this->ajaxReturn(0, 'success', ['user_type'=> 0, 'url'=> '']);
        }

        $wxappConfig = SmsConfigModel::getConfByIndex('wxapp');

        $data = [
            'appid' => $wxappConfig['username'],
            'redirect_uri'  => 'http://cvgshop.czxb.com/',
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
            'state' => $this->user_info['user_id']
        ];

        $wxApp = new \Vendor\ext\Wxapp($wxappConfig['username'], $wxappConfig['password']);
        $url = $wxApp->oauth($data);

        $pic_name = base64_encode(md5($userInfo['user_id'])) . ".png";
        $config = \Yaf\Application::app()->getConfig();

        $path = $config['upload']['path'] . "/qrcode/" . $pic_name;

        \Vendor\QRcode::png($url, $path, 'L', 6, 2);
        $img_url = '/upload/qrcode/'. $pic_name;

        $this->ajaxReturn(0, 'success', ['user_type'=> $userInfo['user_type'], 'url'=> $img_url, 'link'=> $url]);
    }

    public function shareAction(){
        $wxApp = new \Vendor\ext\Wxapp();
        $qrUrl = $wxApp->qrcode( $this->user_info['user_id']);
        $this->ajaxReturn(0, 'success', ['url'=> $qrUrl]);
    }

    //保存店铺轮播图
    public function delshopgalleryimgAction(){
        $params = $this->post('', '', false);
        if(!isset($params['gallery_img'])){
            $this->ajaxReturn(400, '未获取到轮播图');
        }
        $userInfo = UserModel::getSingleton()->find(['user_id'=> $this->user_info['user_id']], 'shop_id');
        if(!ShopModel::getSingleton()->update(['shop_id'=> $userInfo['shop_id']], ['gallery_img'=> $params['gallery_img']])){
            $this->ajaxReturn(400, '操作失败');
        }
        $this->ajaxReturn(0, '操作成功');
    }
}
